<?php

/**
 * 微信公共函数类
 * Class WxFunction
 */
class WxFunction
{

    /**
     * CURL GET
     * @param string $url
     * @return string
     */
    public static function curlGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    /**
     * CURL POST
     * @param string       $url
     * @param string|array $data
     * @return string
     */
    public static function curlPost($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_POST, 1);
        if (is_array($data)){
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        } else {
            curl_setopt($curl, CURLOPT_POSTFIELDS, (string)$data);
        }
        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    /**
     * 记录日志
     * @param string|array $data
     * @param string       $rank
     */
    public static function log($data, $rank = 'info')
    {
        $path = dirname(__FILE__) . '/log/';
        if ( !is_dir($path)) @mkdir($path, 0777, TRUE);
        if (is_array($data)) $data = json_encode($data);

        $data = '[' . strtoupper($rank) . '] --> ' . date('H:i:s') . ' --> ' . $data;

        $path = $path . date('Ymd') . '.php';
        if ( !file_exists($path)){
            // <style>标签可以使phpStorm支持日志信息高亮
            @file_put_contents($path, '<?php exit(\'404 Not Found\'); ?><style>' . PHP_EOL . PHP_EOL);
        }
        @file_put_contents($path, $data . PHP_EOL, FILE_APPEND);
    }

    /**
     * 跳转回调url，并以正确方式传递数据
     * @param string $callback_url
     * @param array  $data
     */
    public static function callback($callback_url, $data)
    {
        require_once 'WxAes.php';
        WxAes::$_key = WxConfig::KEY;

        // 只加密、返回指定字段数据
        $data = array(
            'openid'     => $data['openid'],
            'nickname'   => $data['nickname'],
            'sex'        => $data['sex'],
            'province'   => $data['province'],
            'city'       => $data['city'],
            'country'    => $data['country'],
            'headimgurl' => $data['headimgurl'],
        );

        foreach ($data as $k => $v){
            $data[$k] = WxAes::encrypt($v);
        }

        if (strpos($callback_url, '?') === FALSE){
            $callback_url .= '?';
        } else {
            $callback_url .= '&';
        }

        header('Location: ' . $callback_url . http_build_query($data));
        exit;
    }

    /**
     * 缓存。参数2为空时表示获取，否则为设置。
     * 设置缓存时返回bool。读取缓存时返回null或array
     * @param string     $name
     * @param array|null $data
     * @return bool|null|array
     */
    public static function cache($name, $data = NULL)
    {
        $path = 'cache';
        // 创建缓存目录
        if ( !is_dir($path)) @mkdir($path, 0777, TRUE);
        $path .= '/' . $name;

        require_once 'WxAes.php';
        WxAes::$_key = WxConfig::KEY;
        if (isset($data)){
            // 存
            $data = json_encode($data);
            $data = WxAes::encrypt($data);
            return @file_put_contents($path, $data) === FALSE ? FALSE : TRUE;
        } else {
            // 取
            if ( !file_exists($path) || !is_readable($path)) return NULL;
            $data = WxAes::decrypt(file_get_contents($path));
            $data = json_decode($data, TRUE);
            return $data;
        }
    }

    /**
     * 校验签名
     * @param string $sign
     * @return bool
     */
    public static function verify($sign)
    {
        $data = $_GET['get'] . WxConfig::KEY . $_GET['ts'];
        $data = md5(strtolower($data));
        return $sign == $data;
    }

    /**
     * AJAX格式返回数据
     * @param null|string|array $result
     * @param string            $msg
     * @param int               $code
     */
    public static function ajaxReturn($result = NULL, $msg = '', $code = 0)
    {
        if ($msg !== '' && $code == 0){
            $code = 1; // 默认错误代码
        }
        exit(json_encode(array(
            'errorCode' => $code,
            'errorMsg'  => $msg,
            'result'    => $result,
        )));
    }
}